<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="108px"
    >
      <el-form-item label="合同类型" prop="contractType">
        <el-select v-model="queryParams.contractType" class="!w-240px" placeholder="请选择合同类型">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.BIZ_CONTRACT_ARCHIVE_CONTRACT_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="合同名称" prop="contractName">
        <el-input
          v-model="queryParams.contractName"
          placeholder="请输入合同名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="合同编号" prop="contractCode">
        <el-input
          v-model="queryParams.contractCode"
          placeholder="请输入合同编号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="合同状态" prop="status">
        <el-select v-model="queryParams.status" class="!w-240px" placeholder="请选择合同状态">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.BIZ_CONTRACT_ARCHIVE_CONTRACT_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="签约时间" prop="signTime">
        <el-date-picker
          v-model="queryParams.signTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="管理单元名称" prop="manageUnitName">
        <el-input
          v-model="queryParams.manageUnitName"
          placeholder="请输入管理单元名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['san:biz-contract-archive:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['san:biz-contract-archive:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
        <el-button
          type="danger"
          plain
          :disabled="isEmpty(checkedIds)"
          @click="handleDeleteBatch"
          v-hasPermi="['san:biz-contract-archive:delete']"
        >
          <Icon icon="ep:delete" class="mr-5px" /> 批量删除
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      row-key="id"
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
      @selection-change="handleRowCheckboxChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column label="合同名称" align="center" prop="contractName" width="350" />
      <el-table-column label="合同编号" align="center" prop="contractCode" width="350" />
      <el-table-column label="合同类型" align="center" prop="contractType" width="200">
        <template #default="scope">
          <dict-tag
            :type="DICT_TYPE.BIZ_CONTRACT_ARCHIVE_CONTRACT_TYPE"
            :value="scope.row.contractType"
          />
        </template>
      </el-table-column>
      <el-table-column label="合同状态" align="center" prop="status" width="100px">
        <template #default="scope">
          <dict-tag
            :type="DICT_TYPE.BIZ_CONTRACT_ARCHIVE_CONTRACT_STATUS"
            :value="scope.row.status"
          />
        </template>
      </el-table-column>
      <el-table-column label="签约时间" align="center" prop="signTime" width="200px">
        <template #default="scope">
          {{ formatDate(scope.row.signTime, 'YYYY-MM-DD') }}
        </template>
      </el-table-column>
      <el-table-column label="合同开始时间" align="center" prop="contractStartTime" width="200px">
        <template #default="scope">
          {{ formatDate(scope.row.contractStartTime, 'YYYY-MM-DD') }}
        </template>
      </el-table-column>
      <el-table-column label="合同终止时间" align="center" prop="contractEndTime" width="200px">
        <template #default="scope">
          {{ formatDate(scope.row.contractEndTime, 'YYYY-MM-DD') }}
        </template>
      </el-table-column>
      <el-table-column label="审核失败原因" align="center" prop="auditFailedReason" />
      <!-- <el-table-column
        label="合同上交时间"
        align="center"
        prop="contractSubmitTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column
        label="合同归档时间"
        align="center"
        prop="contractCompleteTime"
        :formatter="dateFormatter"
        width="180px"
      /> -->
      <el-table-column label="支出" align="center">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openExpenseDialog(scope.row.id)"
            v-hasPermi="['san:biz-contract-archive:expense']"
          >
            明细
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" min-width="400px">
        <template #default="scope">
          <el-button
            v-if="scope.row.status == '0' || scope.row.status == '1'"
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['san:biz-contract-archive:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['san:biz-contract-archive:delete']"
          >
            删除
          </el-button>
          <el-button
            v-if="scope.row.status == '0'"
            link
            type="primary"
            @click="handleChangeContractStatus(scope.row.id, '1')"
            v-hasPermi="['san:biz-contract-archive:submitAudit']"
          >
            提交
          </el-button>
          <el-button
            v-if="scope.row.status == '1'"
            link
            type="primary"
            @click="handleChangeContractStatus(scope.row.id, '2')"
            v-hasPermi="['san:biz-contract-archive:audit']"
          >
            审核
          </el-button>
          <el-button
            v-if="scope.row.status == '1'"
            link
            type="primary"
            @click="openAuditDialog(scope.row.id)"
            v-hasPermi="['san:biz-contract-archive:audit']"
          >
            驳回
          </el-button>
          <el-button
            v-if="scope.row.status == '3'"
            link
            type="primary"
            @click="openForm('renew', scope.row.id)"
            v-hasPermi="['san:biz-contract-archive:renew']"
          >
            续签
          </el-button>
          <el-button
            v-if="scope.row.status != '4'"
            link
            type="primary"
            @click="handleChangeContractStatus(scope.row.id, '4')"
            v-hasPermi="['san:biz-contract-archive:finish']"
          >
            结束
          </el-button>
          <el-button
            v-if="scope.row.status == '0' || scope.row.status == '1'"
            link
            type="primary"
            @click="handleChangeContractStatus(scope.row.id, '5')"
            v-hasPermi="['san:biz-contract-archive:churn']"
          >
            流失
          </el-button>
          <el-button
            link
            type="primary"
            @click="handleChangeContractStatus(scope.row.id, '6')"
            v-hasPermi="['san:biz-contract-archive:invalid']"
          >
            无效
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <ContractArchiveForm ref="formRef" @success="getList" />
  <ContractArchiveExpenseDialog ref="expenseDialogRef" @success="getList" />
  <AuditDialog ref="auditDialogRef" @success="getList" />
</template>

<script setup lang="ts">
import { isEmpty } from '@/utils/is'
import { dateFormatter } from '@/utils/formatTime'
import { formatDate } from '@/utils/formatTime'
import download from '@/utils/download'
import { ContractArchiveApi, ContractArchive } from '@/api/biz/contract/'
import ContractArchiveForm from './ContractArchiveForm.vue'
import ContractArchiveExpenseDialog from './ContractArchiveExpenseDialog.vue'
import AuditDialog from './AuditDialog.vue'
import { DICT_TYPE, getIntDictOptions, getStrDictOptions } from '@/utils/dict'

/** 合同档案 列表 */
defineOptions({ name: 'ContractArchive' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<ContractArchive[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  contractName: undefined,
  contractCode: undefined,
  customerId: undefined,
  customerName: undefined,
  signTime: [],
  powerAccount: undefined,
  projectCode: undefined,
  customerDirectorName: undefined,
  contactNumber: undefined,
  companyDirectorName: undefined,
  manageUnitId: undefined,
  manageUnitName: undefined,
  costomerManager: undefined,
  powerLocation: undefined,
  powerAddress: undefined,
  powerArea: undefined,
  serviceContent: undefined,
  supplement: undefined,
  transformerAmount: undefined,
  totalVolume: undefined,
  measureAmount: undefined,
  contractStartTime: [],
  contractEndTime: [],
  contractMonthNumber: undefined,
  contractMonthText: undefined,
  feePerMontNumber: undefined,
  feePerMontText: undefined,
  factFeePerMonthNumber: undefined,
  factFeePerMonthText: undefined,
  contractPriceNumber: undefined,
  contractPriceText: undefined,
  firstPay: undefined,
  firstPayDate: [],
  instalmentCount: undefined,
  receiveInterval: undefined,
  intervalPay: undefined,
  serviceUnitId: undefined,
  serviceManagerName: undefined,
  introducer: undefined,
  introduceChannel: undefined,
  remark: undefined,
  attachmentUrl: undefined,
  createTime: [],
  ownerUserId: undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await ContractArchiveApi.getContractArchivePage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 打开支出对话框 */
const expenseDialogRef = ref()
const openExpenseDialog = (id?: number) => {
  expenseDialogRef.value.open(id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await ContractArchiveApi.deleteContractArchive(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 批量删除合同档案 */
const handleDeleteBatch = async () => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    await ContractArchiveApi.deleteContractArchiveList(checkedIds.value)
    message.success(t('common.delSuccess'))
    await getList()
  } catch {}
}

const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records: ContractArchive[]) => {
  checkedIds.value = records.map((item) => item.id)
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await ContractArchiveApi.exportContractArchive(queryParams)
    download.excel(data, '合同档案.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

const handleChangeContractStatus = async (id: number, status: String) => {
  const data = {
    id: id,
    status: status
  } as unknown as ContractArchive
  await message.confirm(`您确定要执行该操作吗？`)
  await ContractArchiveApi.changeStatus(data)
  message.success('操作成功')
  await getList()
}

/** 打开支出对话框 */
const auditDialogRef = ref()
const openAuditDialog = (id?: number) => {
  auditDialogRef.value.open(id)
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>
